package com.hy.admin.security.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import com.hy.admin.security.oauth.CustomJdbcClientDetailsService;
import com.hy.admin.security.oauth.CustomJdbcTokenStore;
import com.hy.admin.security.service.impl.MyUserDetailService;

/**
 * 认证服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthenticatiionServerConfig extends AuthorizationServerConfigurerAdapter{

	@Autowired
    private AuthenticationManager authenticationManager;
	@Autowired
	private CustomJdbcClientDetailsService clientDetailsService;
	
	@Autowired
	private CustomJdbcTokenStore tokenStore;
	
	@Autowired
	private CustomTokenEnhancer tokenEnhancer;
	
//	@Autowired
//	private DefaultTokenServices tokenService;
	
	@Autowired
    private MyUserDetailService userDetailsService;
	
	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		super.configure(clients);
		clients.withClientDetails(clientDetailsService);
		
//		clients.inMemory()
//		.withClient("mobile_client")
//        .resourceIds("mobile-resource")
//        .authorizedGrantTypes("password", "refresh_token")
//        .scopes("select")
//        .authorities("client")
//        .secret("mobile")
//        .autoApprove(true);
        //.accessTokenValiditySeconds(TOKEN_VALIDITY_SECONDS)
	}
	
	 @Bean
     public WebResponseExceptionTranslator webResponseExceptionTranslator() {
         return new CustomWebResponseExceptionTranslator();
     }
	
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints
		.tokenStore(tokenStore)
		.exceptionTranslator(webResponseExceptionTranslator())
		.authenticationManager(authenticationManager)
		.tokenEnhancer(tokenEnhancer)
		.userDetailsService(userDetailsService); //配置userService 这样每次认证的时候会去检验用户是否锁定，有效等

	}
	
	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//		super.configure(security);
		security.allowFormAuthenticationForClients();
	}
	
}
